
//
//  YYYEmoticonModel.swift
//  HotNews
//
//  Created by yang on 2017/11/5.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

class YYYEmoticonModel: NSObject {

    //表情使用次数
    var times: Int = 0
    
    //表情类型 0:图片 1:表情
    var type = false
    
    //本地图文混排的表情图片名称
    var png: String?
    
    //表情的中文字符串，发给新浪微博服务器，节约流量
    var chs: String?
    
    //emoji字符串
    var emoji: String?
    
    //表情对应的十六进制编码
    var code: String?
    {
        didSet
        {
            guard let code = code else
            {
                return
            }
            let scanner = Scanner(string: code)
            var result: UInt32 = 0
            scanner.scanHexInt32(&result)
            let c = Character(UnicodeScalar(result)!)
            emoji = String(c)
        }
    }
    
    //表情所在目录
    var directory: String?
    
    //图像
    var image: UIImage?
    {
        if type
        {
            //表情
            return nil
        }
        guard let directory = directory,
              let png = png,
              let path = Bundle.main.path(forResource: "HMEmoticon.bundle", ofType: nil),
              let bundle = Bundle(path: path) else
        {
            return nil
        }
        let imageName = "\(directory)/\(png)"
        let image = UIImage(named: imageName, in: bundle, compatibleWith: nil)
        return image
    }
    
    //图像文本
    func imageText(font: UIFont) -> NSAttributedString
    {
        guard let image = image else {
            return NSAttributedString(string: "")
        }
        //文本附件
        let attachment = EmoticonTextAttachment()
        attachment.chs = chs
        attachment.image = image
        attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
        
        //属性文本
        let attributedString = NSAttributedString(attachment: attachment)
        let mutableAttributed = NSMutableAttributedString(attributedString: attributedString)
        mutableAttributed.addAttributes([NSAttributedStringKey.font : font], range: NSRange(location: 0, length: 1))
        
        return NSAttributedString(attributedString: mutableAttributed)
    }
    override var description: String
    {
        return yy_modelDescription()
    }
}
